package dao;

import dao.inte.ConfigurationRepository;
import domain.MyConfiguration;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Singleton;
import javax.persistence.NoResultException;
import java.util.logging.Level;
import java.util.logging.Logger;

@Singleton
public class ConfigurationRepositoryImpl extends AbstractEntityRepository<MyConfiguration> implements ConfigurationRepository {
    public final static Logger logger = Logger.getLogger(ConfigurationRepositoryImpl.class.getName());


    public ConfigurationRepositoryImpl() {
        super(MyConfiguration.class);
    }

    @Override
    protected Class<MyConfiguration> getEntityClass() {
        return MyConfiguration.class;
    }

    @SuppressWarnings("unchecked")
    @Transactional
    public MyConfiguration getConfig() {
        MyConfiguration configuration;
        configuration = findById(Long.valueOf(1));
        if (configuration == null) {
            try {
                configuration = (MyConfiguration) entityManager.createQuery("from " + getEntityClass().

                        getCanonicalName()).
                        getSingleResult();
            } catch (NoResultException e) {
                configuration = new MyConfiguration();
                try {
                    configuration = save(configuration);
                } catch (Exception e1) {
                    logger.log(Level.SEVERE, null, e1);
                }
            }
        }
        if (configuration.getId() != 1) {
            logger.log(Level.SEVERE, "Configuration has wrong ID, it has to be 1, instead of " + configuration.getId(), "Configuration has wrong ID, it has to be 1, instead of " + configuration.getId());
        }
        return configuration;
    }
}
